package com.kitchen.network;

import com.kitchen.service.OrderService;
import com.kitchen.util.FileUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 订单服务器类 - 网络编程实现
 * 使用多线程处理客户端连接
 */
public class OrderServer {
    private int port;
    private OrderService orderService;
    private ExecutorService threadPool;
    private boolean running;
    
    public OrderServer(int port) {
        this.port = port;
        this.orderService = new OrderService();
        this.threadPool = Executors.newFixedThreadPool(10);
        this.running = false;
    }
    
    public void start() {
        running = true;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            FileUtil.writeLog("订单服务器启动，监听端口: " + port);
            System.out.println("订单服务器启动，监听端口: " + port);
            
            while (running) {
                Socket clientSocket = serverSocket.accept();
                threadPool.execute(new ClientHandler(clientSocket, orderService));
            }
        } catch (IOException e) {
            FileUtil.writeLog("服务器启动失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
    
    public void stop() {
        running = false;
    }
    
    /**
     * 客户端处理线程
     */
    private static class ClientHandler implements Runnable {
        private Socket socket;
        private OrderService orderService;
        
        public ClientHandler(Socket socket, OrderService orderService) {
            this.socket = socket;
            this.orderService = orderService;
        }
        
        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                
                String request = in.readLine();
                FileUtil.writeLog("收到客户端请求: " + request);
                
                // 简单的请求处理
                if ("GET_ORDERS".equals(request)) {
                    String response = "订单数量: " + orderService.getAllOrders().size();
                    out.println(response);
                } else {
                    out.println("未知请求: " + request);
                }
                
            } catch (IOException e) {
                FileUtil.writeLog("处理客户端请求失败: " + e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

